package com.shareyi.netty.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 描述
 *
 * @author zhangshibin
 * @since 2018/9/21
 */
public class EchoClient {


    public void connect(String host, int port) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup(); // (1)
        try {
            Bootstrap b = new Bootstrap(); // (2)
            b.group(group)
                    .channel(NioSocketChannel.class) // (3)
                    .handler(new ChannelInitializer<SocketChannel>() { // (4)
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    })
                    .option(ChannelOption.TCP_NODELAY, true);     // (5)

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.connect(host, port).sync(); // (7)
            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8084;
        }
        new EchoClient().connect("127.0.0.1", port);
    }
}
